import AsyncStorage from '@react-native-async-storage/async-storage';

let cache = {}

const init = async () => {
    let keys = await AsyncStorage.getAllKeys()
    let items = await AsyncStorage.multiGet(keys)
    items.map(([key, value]) => {
        try {
            let jsonValue = JSON.parse(value)
            cache[key] = jsonValue
        } catch (error) {
            cache[key] = value
        }
    })
}

const setStringValue = (key, value) => {
    if (cache[key] === value) {
        return
    } else {
        cache[key] = value
        AsyncStorage.setItem(key, value).catch(error => { throw error })
    }
}

const setObjectValue = (key, value) => {
    try {
        if (cache[key] === value) {
            return
        } else {
            cache[key] = value
            let value1 = JSON.parse(JSON.stringify(value))
            const jsonValue = JSON.stringify(value1)
            AsyncStorage.setItem(key, jsonValue)
        }
    } catch (e) {
        throw error
    }
}

const getValue = (key) => {
    return cache[key]
}

const removeValue = (key) => {
    delete cache[key]
    AsyncStorage.removeItem(key).catch(error => { throw error })
}

const replaceValue = (key, value) => {
    try {
        if (cache[key] === value) {
            return
        } else {
            let value1 = JSON.parse(JSON.stringify(value))
            cache[key] = value1
            AsyncStorage.removeItem(key).then(() => {
                const jsonValue = JSON.stringify(value)
                AsyncStorage.setItem(key, jsonValue)
            })
        }
    } catch (error) {
        throw error
    }
}

const clearAll = async () => {
    cache = {}
    AsyncStorage.clear().catch(error => { throw error })
}

export {
    setStringValue,
    setObjectValue,
    getValue,
    removeValue,
    clearAll,
    init,
    replaceValue
}